package de.rockon.fuzzy.controller.gui.tools;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import de.rockon.fuzzy.controller.model.FuzzyController;
import de.rockon.fuzzy.controller.model.FuzzyVariable;
import de.rockon.fuzzy.controller.util.Logger;
import de.rockon.fuzzy.controller.util.factories.UIFactory;
import de.rockon.fuzzy.exceptions.RuleMissingValuesException;
import de.rockon.fuzzy.exceptions.ValueOutOfDomainException;

public class FuzzyTestCase {
	
	private String identifier;
	
	private HashMap<FuzzyVariable, Double> testValues = new HashMap<FuzzyVariable, Double>();
	
	private HashMap<FuzzyVariable, Double> testResults = new HashMap<FuzzyVariable, Double>();
	
	private DecimalFormat df = new DecimalFormat("0.00");
	
	public FuzzyTestCase(final String identifier) {
		this.identifier = identifier;
	}
	
	public void addTestValueForVariable(final FuzzyVariable variable, final Double value) {
		testValues.put(variable, value);
	}

	public double getValueForVariable(final FuzzyVariable variable) {
		return testValues.get(variable);
	}
	
	public String getIdentifier() {
		return identifier;
	}

	public void runTest() {
		try {
			HashMap<FuzzyVariable, Double> dataBuffer = FuzzyController.getInstance().handleProcessInput(testValues);
			
			for (FuzzyVariable var : dataBuffer.keySet()) {
				Logger.info("Output value " + var.getName() + ": " + df.format(dataBuffer.get(var)) + " " + var.getUnit());
				testResults.put(var, dataBuffer.get(var));
			}
			
		} catch (ValueOutOfDomainException e1) {
			e1.printStackTrace();
		} catch (RuleMissingValuesException e2) {
			Logger.debug(e2.getMessage());
		}
	}
	
	public String getResultValueForVariable(FuzzyVariable fuzzyVariable) {
		if (fuzzyVariable == null || testResults.get(fuzzyVariable) == null) return "";
		return df.format(testResults.get(fuzzyVariable));
	}

	@Override
	public String toString() {
		StringBuffer buf = new StringBuffer();
		buf.append(identifier + ":\n");
		
		for (Entry<FuzzyVariable, Double> entry : testValues.entrySet()) {
			buf.append(entry.getKey().getName() + 
					" = " 
					+ entry.getValue() + "\n");
		}
		
		buf.append("-------------------\n");
		return buf.toString();
	}
}